<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>用户管理</title>
    <link rel="stylesheet" type="text/css" href="./css/main.css" />
    <link rel="stylesheet" type="text/css" href="./layui/css/layui.css" />
    <link rel="stylesheet" type="text/css" href="./css/layuiAdminTheme.css" />
    <style type="text/css">
      .layui-form-label {
        width: auto !important;
      }

      .operation span:last-of-type {
        color: #F5222D;
      }

      .pageNav {
        margin: 0 auto;
        width: fit-content;
      }

      .pageNav a,
      .operation span {
        cursor: pointer;
        display: inline-block;
      }

      cite {
        cursor: default;
      }

      td
      {
        white-space: nowrap;
        text-align: center;
      }
    </style>
  </head>
  <body>
    <script src="./js/main.js" charset="utf-8"></script>
<!--    <script src="https://cdn.jsdelivr.net/npm/jquery" charset="utf-8"></script>-->
    <script src="./layui/layui.js" charset="utf-8"></script>
    <script src="./js/jQuery.main.js"></script>
    <script src="./js/xm-select.js"></script>

    <form class="layui-form" action="" lay-filter="data">
      <div class="layui-form-item">
        <div class="layui-inline">
          <label class="layui-form-label">搜索：</label>
          <input type="text" name="userName" class="layui-input" style="width: 8em;" placeholder="用户姓名" value="">
        </div>
        <div class="layui-inline">
          <input type="text" name="loginName" class="layui-input" style="width: 10em;" placeholder="登录名（工号）" value="">
        </div>
        <div class="layui-inline">
          <input type="text" name="deptName" class="layui-input" style="width: 8em;" placeholder="部门" value="">
<!--          <select id="deptName" type="text" name="deptName" class="layui-input" style="width: 8em;" lay-filter="deptName">-->
<!--            <option value="">请选择部门...</option>-->
<!--            <option value="电感事业部">电感事业部</option>-->
<!--            <option value="汽车电子事业部">汽车电子事业部</option>-->
<!--            <option value="通信事业部">通信事业部</option>-->
<!--          </select>-->
        </div>
        <div class="layui-inline">
          <input type="text" id="displayLength" name="displayLength" class="layui-input" style="display: none;" placeholder="每页页数" value="10">
          <button type="submit" class="layui-btn" lay-submit="" lay-filter="searchBtn">搜索用户</button>
        </div>
      </div>
    </form>
    <table class="layui-table" lay-skin="line">
      <thead>
        <tr>
          <th style="text-align: center">用户姓名</th>
          <th style="text-align: center">登录名(工号)</th>
          <th style="text-align: center">部门</th>
          <th style="text-align: center">创建者</th>
          <th style="text-align: center">创建时间</th>
          <th style="text-align: center">使用状态</th>
          <th style="text-align: center">作业站台</th>
          <th style="text-align: center">操作</th>
        </tr>
      </thead>
      <tbody></tbody>
    </table>
    <div style="display: flex;">
      <div style="flex: 1">
        <div class="pageNav">
          <span class="layui-breadcrumb" lay-separator="-">
            <a class="fristPage">首页</a>
            <a class="lastPage">上一页</a>
            <a><cite>第<span id="page"></span>页</cite></a>
            <a class="nextPage">下一页</a>
            <a class="endPage">尾页</a>
          </span>
        </div>
      </div>
    </div>

    <script type="text/javascript">
      var displayStart = 1;
      var endPage = null;
      var layer = layui.layer;
      var form = null;
      var list = null;



      layui.use(['form', 'element'], function() {
        form = layui.form;

        search(1);

        form.on('submit(searchBtn)', function() {
          search(1);
          return false;
        });
        $('.fristPage').click(function() {
          search(1);
          return false;
        });
        $('.lastPage').click(function() {
          search((displayStart > 1 ? displayStart - 1 : 1));
          return false;
        });
        $('.nextPage').click(function() {
          search((displayStart < endPage ? displayStart + 1 : endPage));
          return false;
        });
        $('.endPage').click(function() {
          search(endPage);
          return false;
        })
      })

      function deleteUser(index) {
        if (!index) return false;
        let confirm1=layer.confirm('您确定要删除该用户吗？', {
                  btn: ['确定','取消']
                },function () {
          $.ajax({
            url: url + '/sys-user/delete',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({
              userId: sessionStorage.getItem('userId'),
              goalId: index
            }),
            success: function (res) {
              layer.msg(res.msg)
              if (res.code == 200) search();
            }
          })
          layer.close(confirm1);
        }
        ,function (){
          layer.close(confirm1);
        }
        )
      }

      function addAdmin(index) {
        $.ajax({
          url: '/sys-user/getAdmin/'+sessionStorage.getItem('userId'),
          method: 'GET',
          contentType: 'application/json',
          success: function (res) {
            if (res.code===200){
              layer.open({
                type: 1,
                skin: 'layui-layer-rim',
                area: ['700px', '350px'],
                title: '授权用户',
                content: `
               <form class="layui-form" action="" lay-filter="addAdmin">
                <div class="layui-row" style="margin: 15px">
                <div class="layui-col-md6"><label class="layui-form-label">用户名：</label>
                <div class="layui-input-inline " style="width: 5em" >
                <input id="userNameOfAdd" type="text" name="userNameOfAdd" placeholder="用户名" lay-verify="required" class="layui-input" style="width: 12em !important;" readonly="readonly">
                </div></div>
                <div class="layui-col-md6"><label class="layui-form-label">工号：</label>
                <input id="loginNameOfAdd" type="text" name="loginNameOfAdd" placeholder="工号" lay-verify="required" class="layui-input" style=" width: 12em !important;" readonly="readonly">
                </div>
                </div>

                <div class="layui-row">
                <div class="layui-col-md6"><label class="layui-form-label">现在权限：</label>
                <div class="layui-input-inline " style="width: 15em">
                <input id="typeOfAdd" type="text" name="typeOfAdd" placeholder="现在权限" lay-verify="required" class="layui-input" style="width: 13em !important;" readonly="readonly">
                </div></div>
                <div class="layui-col-md6"><label class="layui-form-label">来自部门：</label>
                <input id="deptOfAdd" type="text" name="deptOfAdd" placeholder="来自部门" lay-verify="required" class="layui-input" style="width: 10em !important;" readonly="readonly">
                </div>
                </div>

                <div style="margin: 15px">
                <label class="layui-form-label" style="color: #FD482C">*  授予权限：</label>
                <div class="layui-input-inline " style="width: 15em">
                <select name="type" id="type" lay-verify="required" lay-filter="type" lay-search="">
                    <option value="">请赋予权限...</option>
                    <option value="0">二级管理员</option>
                    <option value="2">普通作业员</option>
                </select>
                </div></div>

                <div align="center" style="margin:30px 0">
                 <button id="submit" type="submit" class="layui-btn" lay-submit="" lay-filter="addAdminBtn" >授权</button>
                 <button class="layui-btn layui-btn-danger" onclick="layer.close(layer.index)">取消</button></div>

                 </form>
            `,

                success: function(){
                  $.ajax({
                    url: url + '/sys-user/getUserInfoById/' + index,
                    contentType: 'application/json',
                    async: false,
                    success: function (res) {
                      $('#userNameOfAdd').val(res.data.userName);
                      $('#loginNameOfAdd').val(res.data.loginName);
                      $('#typeOfAdd').val(adminLevel(res.data.type));
                      $('#deptOfAdd').val(res.data.deptName);
                      form.render()
                    }
                  })
                }
              })
            }
            else if (res.code===400){
              layer.msg("权限不足");
            }
          }
        })

        form.on('submit(addAdminBtn)', function(data) {
          console.log("校验通过，准备提交");
          var data = form.val("addAdmin");
          data.goalId=index;
          data.type=$('#type').val();
          let confirm1=layer.confirm('确定为其授权吗?', {
            btn: ['确定','取消']},function(){
            $.ajax({
              url: url + '/sys-user/addAdmin',
              method: 'POST',
              contentType: 'application/json',
              async: false,
              data: JSON.stringify(data),
              success: function(res) {
                if (res.code == 200) {
                  parent.layer.alert(res.msg, {
                    end: function(){
                      location.reload();
                    }
                  });
                }else
                  layer.msg(res.msg);
              }
            })
            layer.close(confirm1);
          },function () {
            layer.close(confirm1);
          })
          return false;
        })
      }

      function editUser(index) {
        $.ajax({
          url: '/sys-user/getAdmin/'+sessionStorage.getItem('userId'),
          method: 'GET',
          contentType: 'application/json',
          success: function (res) {
            if (res.code===200) {
              layer.open({
                type: 1,
                skin: 'layui-layer-rim',
                area: ['600px', '550px'],
                title: '用户信息修改',
                content: `
               <div class="layui-tab">
                <ul class="layui-tab-title">
                    <li class="layui-this">基础信息修改</li>
                    <li>用户密码修改</li>
                </ul>
                <div class="layui-tab-content">
                  <div class="layui-tab-item layui-show">
                 <form class="layui-form" action="" lay-filter="editUserInfo">
                  <div>
                  <label class="layui-form-label">用户名：</label>
                    <input id="userNameOfEdit" type="text" name="userNameOfEdit" placeholder="请输入用户名..." lay-verify="required" class="layui-input" style="width: 12em !important;">
                  </div>

                  <div style="margin: 15px">
                  <label class="layui-form-label">工号：</label>
                    <input id="loginNameOfEdit" type="text" name="loginNameOfEdit" placeholder="请输入工号..." lay-verify="required" class="layui-input" style=" width: 12em !important;">
                  </div>

                  <div style="margin: 15px;">
                  <label class="layui-form-label">部门：</label>
                  <div class="layui-inline" style="width: 15em">
                    <select name="deptNameOfEdit" id="deptNameOfEdit"  lay-verify="required" lay-filter="deptId" lay-search="">
                        <option value="">请选择部门...</option>
                    </select>
                  </div></div>

                  <div class="layui-form-item">
                    <label class="layui-form-label">可用:</label>
                    <div class="layui-input-block">
                      <input type="checkbox" id="status" name="status" lay-skin="switch">
                    </div>
                  </div>

                  <div class="layui-form-item">
                    <label class="layui-form-label">作业站位:</label>
                    <div class="layui-input-block">
                      <div id="workScope"></div>
                    </div>
                  </div>
                  <div align="center" style="margin:30px 0">
                    <button id="submit" type="submit" class="layui-btn" lay-submit="" lay-filter="changeBtn" >确定修改</button>
                  </div>
                  </form>
                  </div>
                  <div class="layui-tab-item">
                  <form class="layui-form" action="" lay-filter="changePassWord">
                  <div>
                  <label class="layui-form-label">现密码：</label>
                    <input id="nowPsw" type="text" name="nowPsw" placeholder="现密码.." lay-verify="required" class="layui-input" style="width: 12em !important;" readonly="readonly">
                  </div>

                  <div style="margin: 15px">
                  <label class="layui-form-label">新密码：</label>
                    <input id="newPsw1" type="text" name="newPsw1" placeholder="请输入新密码.." lay-verify="required" class="layui-input" style="width: 12em !important;">
                  </div>

                  <div style="margin: 15px">
                  <label class="layui-form-label">确认新密码：</label>
                    <input id="newPsw2" type="text" name="newPsw2" placeholder="确认新密码.." lay-verify="required" class="layui-input" style="width: 12em !important;">
                  </div>

                  <div align="center" style="margin:30px 0">
                    <button id="submit" type="submit" class="layui-btn" lay-submit="" lay-filter="changePsw" >修改密码</button>
                  </div>
                  </form>
                  </div>
                </div>
               </div>
            `,

                success: function () {
                  $.ajax({
                    url: url + '/sys-user/getUserInfoOfEdit/' + index,
                    contentType: 'application/json',
                    async: false,
                    success: function (res) {
                      $('#userNameOfEdit').val(res.data.userName);
                      $('#loginNameOfEdit').val(res.data.loginName);
                      $('#nowPsw').val(res.data.password);
                      if(res.data.status){
                        $('#status').attr("checked",'true');
                      }
                      $.ajax({
                        url: url + '/sys-dept/listDept',
                        method: 'POST',
                        contentType: 'application/json',
                        success: function (res2) {
                          if (res2.code == 200) {
                            for (var i = 0; i < res2.data.length; i++) {
                              if (res.data.deptName === res2.data[i].dept) {
                                $("#deptNameOfEdit").append("<option selected='selected' value='" + res2.data[i].id + "'>" + res2.data[i].dept +
                                        "</option>");
                              } else {
                                $("#deptNameOfEdit").append("<option value='" + res2.data[i].id + "'>" + res2.data[i].dept +
                                        "</option>");
                              }
                            }
                            form.render('select');
                          }
                        }
                      })
                      //工序下拉框
                      var processList=res.data.workScopes;
                      var processOption = {
                        el: '#workScope',
                        name: 'workScope',//表单的name属性
                        filterable: true,
                        id: 'allProcess',
                        initValue: [ processList[0],processList[1],processList[2],processList[3],processList[4],processList[5],processList[6],processList[7],processList[8],
                          processList[9],processList[10],processList[11],processList[12],processList[13],processList[14],processList[15],processList[16],processList[17],processList[18],
                          processList[19],processList[20],processList[21],processList[22],processList[23],processList[24],processList[25],processList[26],processList[27],processList[28]
                        ],//默认项
                        //layVerify: 'required',//必填项
                        //layVerType: 'tips',//提示类型 同layui
                        tips: '请选择工序...',
                        toolbar: {//工具条,全选,清空,反选,自定义
                          show: true,
                          list: [
                            'ALL',
                            'CLEAR',
                            'REVERSE',
                          ]
                        },
                        data: [],
                      };

                      var process = xmSelect.render(processOption)

                      setTimeout(function(){
                        $.ajax({
                          url: url + '/process-info/listProcessOfUserEdit',
                          method: 'POST',
                          async : false,
                          contentType: 'application/json',
                          data: JSON.stringify({
                            userId: index
                          }),
                          success: function(res) {
                            //data是ajax 异步获取的
                            var data =[];
                            for (var i = 0; i < res.data.length; i++) {
                              data.push({
                                name : res.data[i].processName,
                                value :res.data[i].id
                              });
                            }
                            //模拟通过ajax 获取json数据,异步更新多选下拉框的值
                            process.update({data: data})
                          }
                        })
                      },100);
                      form.render()
                    }
                  })
                }
              })
            }else {
              layer.msg("权限不足")
            }
          }
        })

        form.on('submit(changeBtn)', function(data) {
          var data = form.val('editUserInfo');
          data.userId=index;
          data.userName=$('#userNameOfEdit').val();
          data.loginName=$('#loginNameOfEdit').val();
          data.deptId=$('#deptNameOfEdit').val();
          data.status=$('#status:checked').val();
          $.ajax({
            url: url + '/sys-user/update',
            method: 'POST',
            async: false,
            contentType: 'application/json',
            data: JSON.stringify(data),
            success: function (res) {
              alert(res.msg)
            }
          })
        })

        form.on('submit(changePsw)', function(data) {
          if ($('#newPsw1').val() !==$('#newPsw2').val()){
            alert('两次密码不一致!请注意确认');
          }else{
            var data = form.val('changePassWord');
            data.userId=index;
            data.newPsw=$('#newPsw1').val();
            $.ajax({
              url: url + '/sys-user/changePsw',
              method: 'POST',
              async: false,
              contentType: 'application/json',
              data: JSON.stringify(data),
              success: function (res) {
                if(res.code==200){
                  alert("修改成功")
                }else
                  alert("修改失败，未知错误")
              }
            })
          }
        })
      }

      function search(index) {
        if (!index) var index = displayStart;
        var data = form.val('data');
        data.displayStart = index;
        $.ajax({
          url: url + '/sys-user/listUser',
          method: 'POST',
          async: false,
          contentType: 'application/json',
          data: JSON.stringify(data),
          success: function(res) {
            $('tbody').empty();
            displayStart = res.data.current;
            endPage = res.data.pages;
            list = res.data.records;
            for (var i = 0; i < res.data.records.length; i++) {
              $('tbody').append(
                "<tr>" +
                "<td>" + res.data.records[i].userName +"</td>"+
                "<td>" +res.data.records[i].loginName +"</td>"+
                "<td>" + res.data.records[i].deptName +"</td>"+
                "<td>" + res.data.records[i].createBy +"</td>"+
                "<td>" + res.data.records[i].createTime.replace('T', ' ') +"</td>" +
                "<td>" + userStatus(res.data.records[i].status) +"</td>" +
                "<td>" + res.data.records[i].processName +"</td>" +
                 "<td class='operation'>" +
                      "<button class='layui-btn layui-btn-sm layui-btn-normal' onclick='editUser(" +res.data.records[i].id + ")'>修改</button>" +
                      "<button class='layui-btn layui-btn-sm' style='background-color: #009688' onclick='addAdmin(" +res.data.records[i].id + ")'>授权</button>" +
                      "<button class='layui-btn layui-btn-sm layui-btn-danger' onclick='deleteUser(" +res.data.records[i].id + ")'>删除</button>" +
                 "</td></tr>"
              );
            }
            $('#page').html(displayStart)
          }
        })
      }
    </script>
  </body>
</html>
